import * as $comment from '@/api/comment'
import * as _app from '@/utils/app'
import {ANSWER_ADD_COMMENT_ITEM_FOR_ONE_OF_ANSWERS} from './answer'

const state = {
}

const getters = {
}

const actions = {
  async createForAnswer ({ dispatch, commit, state, rootState, rootGetters, getters }, {answerId, isNeedRedo = false}) {
    let pageProgressId = rootGetters['progress/pageProgressId']
    let textBlocks = rootGetters['progress/textBlocks']
    let contentBlock = textBlocks[pageProgressId]
    let mediaBlocks = rootGetters['progress/mediaBlocks']
    let blocks = _app.getBlocks({ contentBlock, blocks: mediaBlocks[pageProgressId] })
    dispatch('resetValidateError', null, {root: true})

    if (blocks.length === 0) {
      dispatch('addValidateError', '内容不能为空！', {root: true})
    }
    if (rootState.ui.validateErrors.length > 0) return
    dispatch('updateIsLoading', true, {root: true})
    let res = await $comment.createForAnswer({ answerId, isNeedRedo, data: {blocks} })
    dispatch('updateIsLoading', false, {root: true})
    dispatch('progress/updateIsShowReplyForm', false, {root: true})
    dispatch('progress/resetTextBlocks', pageProgressId, {root: true})
    dispatch('progress/setMediaBlocks', {progressId: pageProgressId, blocks: []}, {root: true})
    dispatch('setTriggerClearUploadQueue', null, {root: true})
    dispatch('resetBlocks', null, {root: true})
    commit('answer/' + ANSWER_ADD_COMMENT_ITEM_FOR_ONE_OF_ANSWERS, { answerId, comment: res }, {root: true})
    commit('UI_SET_TOAST_SUCCESS_MSG', '点评成功', {root: true})
  },
}

const mutations = {
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
